package com.bxd.baodan.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.provider.MediaStore;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.app.SharedPreferanceKey;
import com.bxd.baodan.base.SystemBarTintManager;
import com.bxd.baodan.util.FileUtil;
import com.bxd.baodan.util.ImageUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.NetUtil.RequestStringListener;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.StringUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.lang.reflect.Field;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class UserSettingActivity extends BasePreferenceActivity {
    private BroadcastReceiver receiveBroadCast;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preference);
        //initImmersionBar(0);
        initActionBar();
        setActionBarTitle("个人信息");


        addPreferencesFromResource(R.xml.profile_setting);
        getListView().setScrollingCacheEnabled(false);
        getListView().setDivider(
                getResources().getDrawable(R.drawable.listview_divider));
        getListView().setDividerHeight(1);

        initBroadCastReceiver();
    }

    @Override
    @Deprecated
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
                                         Preference preference) {
        if ("my_pic".equals(preference.getKey())) {
            // 处理头像的点击事件
            LogUtil.e("my_pic clicked");
            uploadHeader();
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unRegistReceiver();
    }

    private static final int MSG_BIND_PREFERENCES = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MSG_BIND_PREFERENCES:
                    bindPreferences();
                    break;
            }
        }
    };

    class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (Constant.ACTION_SUCCESS_UPLOAD_INFOR.equals(arg1.getAction())) {
                postBindPreferences();
            }
        }

    }

    private void unRegistReceiver() {
        this.unregisterReceiver(receiveBroadCast);
    }

    private void initBroadCastReceiver() {
        // TODO Auto-generated method stub
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_SUCCESS_UPLOAD_INFOR);
        this.registerReceiver(receiveBroadCast, filter);
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        postBindPreferences();
    }

    private void postBindPreferences() {
        if (mHandler.hasMessages(MSG_BIND_PREFERENCES))
            return;
        mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
    }

    private void bindPreferences() {
        final PreferenceScreen preferenceScreen = getPreferenceScreen();
        if (preferenceScreen != null) {
            preferenceScreen.bind(getListView());
        }
    }

    // 以下为移植过来的

    /**
     * 上传头像
     */
    protected void uploadHeader() {
        new AlertDialog.Builder(this)
                .setTitle("上传头像")
                .setItems(R.array.add_image_type,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                switch (which) {
                                    case 0: // 手机拍照
                                        startActionCamera();
                                        break;
                                    case 1: // 从相册选择
                                        startImagePick();
                                        break;
                                    default:
                                        break;
                                }
                                dialog.cancel();
                            }
                        }).show();
    }

    /**
     * 相机拍照
     */
    protected void startActionCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
        startActivityForResult(intent, ImageUtil.REQUEST_CODE_GETIMAGE_BYCAMERA);
    }

    private Bitmap protraitBitmap;
    private String protraitPath;
    private File protraitFile;
    private Uri origUri;
    private Uri cropUri;

    // 拍照保存的绝对路径
    private Uri getCameraTempFile() {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(Constant.FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            super.showToast("无法保存上传的头像，请检查SD卡是否挂载");
            return null;
        }
        String timeStamp = StringUtil.getTimeStamp();
        // 照片命名
        String cropFileName = "bxd_" + timeStamp + ".jpg";
        // 裁剪头像的绝对路径
        protraitPath = Constant.FILE_SAVEPATH + "/" + cropFileName;
        SpUtil.getInstance().savaString("mytemfile", protraitPath);
        protraitFile = new File(protraitPath);
        cropUri = Uri.fromFile(protraitFile);
        this.origUri = this.cropUri;
        return this.cropUri;
    }

    /**
     * 选择图片裁剪
     */
    protected void startImagePick() {

        Matisse.from(UserSettingActivity.this)
                .choose(MimeType.ofAll(), false)
                .countable(true)
                .capture(false)
                .captureStrategy(
                        new CaptureStrategy(true, "com.bxd.baodan.fileprovider"))
                .maxSelectable(1)
                .gridExpectedSize(
                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(ImageUtil.REQUEST_CODE_GETIMAGE_BYCROP);

    }

    private static final int IMAGE_X = 125;
    private static final int IMAGE_Y = 145;

    /**
     * 拍照后裁剪
     *
     * @param data 原始图片
     * @param
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", IMAGE_X);// 裁剪框比例
        intent.putExtra("aspectY", IMAGE_Y);
        intent.putExtra("outputX", IMAGE_X);// 输出图片大小
        intent.putExtra("outputY", IMAGE_Y);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent, ImageUtil.REQUEST_CODE_GETIMAGE_BYSDCARD);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    // 裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(Constant.FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            showToast("无法保存上传的头像，请检查SD卡是否挂载");
            return null;
        }
        String timeStamp = StringUtil.getTimeStamp();
        String thePath = ImageUtil.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtil.isEmpty(thePath)) {
            thePath = ImageUtil.getAbsoluteImagePath(this, uri);
        }
        String ext = FileUtil.getFileFormat(thePath);
        ext = StringUtil.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "bxd_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = Constant.FILE_SAVEPATH + "/" + cropFileName;
        SpUtil.getInstance().savaString("img_path", protraitPath);
        protraitFile = new File(protraitPath);

        cropUri = Uri.fromFile(protraitFile);
        return this.cropUri;
    }

    /**
     * 上传新照片
     */
    private void uploadNewPhoto() {
        // 获取头像缩略图
        if (!StringUtil.isEmpty(protraitPath) && protraitFile.exists()) {
            protraitBitmap = ImageUtil.loadImgThumbnail(protraitPath, 200, 200);
        } else {
            showToast("图像不存在，上传失败·");
        }
        if (protraitFile == null) {   // FIXME: 2017/7/4 已解决  File.getParent()空指针
            protraitFile = new File(SpUtil.getInstance().getString("img_path"));
        }
        File headerFile = new File(protraitFile.getParent() + "/avatar-"
                + System.currentTimeMillis() + ".jpg");
        protraitFile.renameTo(headerFile);
        protraitFile = headerFile;

        NetUtil netUtil = new NetUtil(this, JsonApi.UPLOAD_AVATAR);
        netUtil.getActivity();
        netUtil.setParams("ver", ver);
        netUtil.setParams("uid", uid);
        netUtil.setParams("pwd", pwd);
        netUtil.setFile("file", protraitFile);
        netUtil.postFile("头像提交中", new RequestStringListener() {
            @Override
            public void onComplete(String result) {


                showToast("上传成功");
                String url = JSONUtil.getData(result).contains("http:")
                        || JSONUtil.getData(result).contains("https:") ?
                        JSONUtil.getData(result) :
                        JsonApi.ROOT_URL + JSONUtil.getData(result);

                LogUtil.e("新的头像路径: " + url);
                LoginInfo
                        .getInstance(UserSettingActivity.this)
                        .getUser()
                        .setUe_avatar(
                                url);
                SpUtil.getInstance().savaString(
                        SharedPreferanceKey.TEMPICURL,
                        url);
                UserSettingActivity.this.sendBroadcast(new Intent(
                        Constant.ACTION_SUCCESS_UPLOAD_INFOR));


            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case ImageUtil.REQUEST_CODE_GETIMAGE_BYCAMERA:
                if (origUri == null) {
                    protraitFile = new File(SpUtil.getInstance().getString(
                            "mytemfile"));
                    origUri = Uri.fromFile(protraitFile);
                }
                startActionCrop(origUri);// 拍照后裁剪
                break;
            case ImageUtil.REQUEST_CODE_GETIMAGE_BYCROP:
                startActionCrop(Matisse.obtainResult(data).get(0));// 选图后裁剪
                break;
            case ImageUtil.REQUEST_CODE_GETIMAGE_BYSDCARD:
                uploadNewPhoto();// 上传新照片
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    String ver, uid, pwd;

    public void setData(String ver, String uid, String pwd) {
        this.ver = ver;
        this.uid = uid;
        this.pwd = pwd;
    }


    /**
     * 沉浸式
     */
    public void initImmersionBar(int color) {
        //当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setTintResource(color == 0 ? R.color.white : color);


        LinearLayout linear_bar = (LinearLayout) findViewById(R.id.bar_hint);
        linear_bar.setVisibility(View.VISIBLE);
        //获取到状态栏的高度
        int statusHeight = getStatusBarHeight();
        //动态的设置隐藏布局的高度
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linear_bar.getLayoutParams();
        params.height = statusHeight;
        linear_bar.setLayoutParams(params);


    }


    /**
     * 通过反射的方式获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    public void initActionBar() {
        ImageView actionBarNewBack = (ImageView) findViewById(R.id.bar_iv_back);
        actionBarNewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

}
